import os
import time

import xlsxwriter
from utils import get_config as GC, common, get_apk_info as apk_base, send_email
from utils.log import info_log, err_info


def send_report(data, start_test_time, start_time, end_time):
    data = get_report(data, start_test_time, start_time, end_time)
    file_path = report(data)
    send_flag = GC.configs['send_email']
    if send_flag == '1':
        subject = 'TRACKPOINT - Field Works App测试报告'
        content = '您好！附件为本次测试的测试报告，请查收！'
        try:
            send_email.send_email(GC.configs['recipient'], subject, content, file_path)
            info_log.info('发送测试报告成功，发送给：{}'.format(GC.configs['recipient']))
        except Exception as e:
            err_info.error(str(e))
    # 删除相关的文件
    OperateFile(common.REPORT_COLLECT_PATH).remove_file()
    OperateFile(common.REPORT_INIT).remove_file()
    OperateFile(common.REPORT_INFO_PATH).remove_file()
    # OperateFile(common.CRASH_LOG_PATH).remove_file()


def read_report(f=""):
    return OperateFile(f, "r").read_txt_row()


def get_report(data, start_test_time, start_time, end_time):
    _read_collect_json = eval(read_report(common.REPORT_COLLECT_PATH))
    for key in _read_collect_json:
        data[key] = _read_collect_json[key]
    apk_msg = apk_base.ApkInfo(GC.configs['app_path_android'])
    data["app_name"] = apk_msg.get_apk_name()
    data["app_size"] = apk_msg.get_apk_size()
    data["app_version"] = apk_msg.get_apk_version()
    data["test_sum_date"] = str(int(end_time - start_time)) + "sec"
    data["test_date"] = start_test_time

    data["init"] = eval(read_report(common.REPORT_INIT))["init"]
    data["info"] = eval(read_report(common.REPORT_INFO_PATH))["info"]
    return data


def report(data):
    file_name = common.REPORT_PATH + time.strftime('%Y-%m-%d') + "_report.xlsx"
    workbook = xlsxwriter.Workbook(file_name)
    worksheet = workbook.add_worksheet("t1")
    worksheet2 = workbook.add_worksheet("t1-details")
    b_OperateReport = OperateReport(wd=workbook, data=data)
    b_OperateReport.init(worksheet)
    b_OperateReport.detail(worksheet2)
    b_OperateReport.close()
    return file_name


def get_format(wd, option={}):
    return wd.add_format(option)


def get_format_center(wd, num=1):
    return wd.add_format({'align': 'center', 'valign': 'vcenter', 'border': num})


def set_border_(wd, num=1):
    return wd.add_format({}).set_border(num)


def _write_center(worksheet, cl, data, wd):
    return worksheet.write(cl, data, get_format_center(wd))


def set_row(worksheet, num, height):
    worksheet.set_row(num, height)


class OperateReport:
    def __init__(self, wd, data):
        self.wd = wd
        self.data = data

    def init(self, worksheet):
        # 设置列行的宽高
        worksheet.set_column("A:A", 15)
        worksheet.set_column("B:B", 20)
        worksheet.set_column("C:C", 20)
        worksheet.set_column("D:D", 20)
        worksheet.set_column("E:E", 20)
        worksheet.set_column("F:F", 20)

        worksheet.set_row(1, 30)
        worksheet.set_row(2, 30)
        worksheet.set_row(3, 30)
        worksheet.set_row(4, 30)
        worksheet.set_row(5, 30)
        worksheet.set_row(6, 30)

        define_format_H1 = get_format(self.wd, {'bold': True, 'font_size': 18})
        define_format_H2 = get_format(self.wd, {'bold': True, 'font_size': 14})
        define_format_H1.set_border(1)

        define_format_H2.set_border(1)
        define_format_H1.set_align("center")
        define_format_H2.set_align("center")
        define_format_H2.set_bg_color("blue")
        define_format_H2.set_color("#ffffff")

        worksheet.merge_range('A1:E1', '测试报告总概况', define_format_H1)
        worksheet.merge_range('A2:E2', '测试概括', define_format_H2)

        _write_center(worksheet, "A3", 'APP名称', self.wd)
        _write_center(worksheet, "A4", 'APP大小', self.wd)
        _write_center(worksheet, "A5", 'APP版本', self.wd)
        _write_center(worksheet, "A6", '测试日期', self.wd)

        _write_center(worksheet, "B3", self.data['app_name'], self.wd)
        _write_center(worksheet, "B4", self.data['app_size'], self.wd)
        _write_center(worksheet, "B5", self.data['app_version'], self.wd)
        _write_center(worksheet, "B6", self.data['test_date'], self.wd)

        _write_center(worksheet, "C3", "用例总数", self.wd)
        _write_center(worksheet, "C4", "通过总数", self.wd)
        _write_center(worksheet, "C5", "失败总数", self.wd)
        _write_center(worksheet, "C6", "测试耗时", self.wd)

        # data1 = {"test_sum": 100, "test_success": 80, "test_failed": 20, "test_date": "2018-10-10 12:10"}
        _write_center(worksheet, "D3", self.data['test_sum'], self.wd)
        _write_center(worksheet, "D4", self.data['test_success'], self.wd)
        _write_center(worksheet, "D5", self.data['test_failed'], self.wd)
        _write_center(worksheet, "D6", self.data['test_sum_date'], self.wd)

        _write_center(worksheet, "E3", "脚本语言", self.wd)

        worksheet.merge_range('E4:E6', 'appium+python3', get_format_center(self.wd))

        # 测试手机详情
        worksheet.merge_range('A9:J9', '测试手机详情', define_format_H2)
        worksheet.set_row(9, 30)
        worksheet.set_row(10, 30)

        _write_center(worksheet, "A10", "手机名字", self.wd)
        _write_center(worksheet, "B10", "运行内存", self.wd)
        _write_center(worksheet, "C10", "CPU", self.wd)
        _write_center(worksheet, "D10", "手机分辨率", self.wd)
        _write_center(worksheet, "E10", "内存占用均值", self.wd)
        _write_center(worksheet, "F10", "内存占用峰值", self.wd)
        _write_center(worksheet, "G10", "CPU占用均值", self.wd)
        _write_center(worksheet, "H10", "CPU占用峰值", self.wd)
        _write_center(worksheet, "I10", "FPS均值", self.wd)
        _write_center(worksheet, "J10", "FPS峰值", self.wd)
        temp = 0
        for item in self.data["init"]:
            worksheet.set_row(11 + temp, 30)
            _write_center(worksheet, "A" + str(11 + temp), item["phone_name"], self.wd)
            _write_center(worksheet, "B" + str(11 + temp), item["phone_raw"], self.wd)
            _write_center(worksheet, "C" + str(11 + temp), item["phone_cpu"], self.wd)
            _write_center(worksheet, "D" + str(11 + temp), item["phone_pix"], self.wd)
            _write_center(worksheet, "E" + str(11 + temp), item["phone_avg_use_raw"], self.wd)
            _write_center(worksheet, "F" + str(11 + temp), item["phone_max_use_raw"], self.wd)
            _write_center(worksheet, "G" + str(11 + temp), item["phone_avg_use_cpu"], self.wd)
            _write_center(worksheet, "H" + str(11 + temp), item["phone_avg_max_use_cpu"], self.wd)
            _write_center(worksheet, "I" + str(11 + temp), item["fps_avg"], self.wd)
            _write_center(worksheet, "J" + str(11 + temp), item["fps_max"], self.wd)
            temp += 1
        # pie(self.wd, worksheet)

    def detail(self, worksheet):
        # 设置列行的宽高
        worksheet.set_column("A:A", 30)
        worksheet.set_column("B:B", 30)
        worksheet.set_column("C:C", 30)
        worksheet.set_column("D:D", 30)
        worksheet.set_column("E:E", 30)
        worksheet.set_column("F:F", 30)
        worksheet.set_column("G:G", 30)
        worksheet.set_column("H:H", 40)
        worksheet.set_column("I:I", 100)
        worksheet.set_column("J:J", 40)

        worksheet.set_row(1, 30)
        worksheet.set_row(2, 30)

        worksheet.merge_range('A1:O1', '测试详情', get_format(self.wd, {'bold': True, 'font_size': 18, 'align': 'center',
                                                                    'valign': 'vcenter', 'bg_color': 'blue',
                                                                    'font_color': '#ffffff'}))
        _write_center(worksheet, "A2", '机型', self.wd)
        _write_center(worksheet, "B2", '用例ID', self.wd)
        _write_center(worksheet, "C2", '模块', self.wd)
        _write_center(worksheet, "D2", '用例介绍', self.wd)
        _write_center(worksheet, "E2", '用例名字', self.wd)
        _write_center(worksheet, "F2", '内存峰值(M)', self.wd)
        _write_center(worksheet, "G2", '内存均值(M)', self.wd)
        _write_center(worksheet, "H2", '失败原因', self.wd)
        _write_center(worksheet, "I2", '提示信息', self.wd)
        _write_center(worksheet, "J2", '结果截图', self.wd)
        temp = 3
        for item in self.data["info"]:
            _write_center(worksheet, "A" + str(temp), item["test_phone_name"], self.wd)
            _write_center(worksheet, "B" + str(temp), item["test_id"], self.wd)
            _write_center(worksheet, "C" + str(temp), item["test_module"], self.wd)
            _write_center(worksheet, "D" + str(temp), item["test_intr"], self.wd)
            _write_center(worksheet, "E" + str(temp), item["test_name"], self.wd)
            _write_center(worksheet, "F" + str(temp), item["test_men_max"], self.wd)
            _write_center(worksheet, "G" + str(temp), item["test_men_avg"], self.wd)
            _write_center(worksheet, "H" + str(temp), item["test_result"], self.wd)
            _write_center(worksheet, "I" + str(temp), item["test_warn_msg"], self.wd)
            _write_center(worksheet, "J" + str(temp), item["test_reason"], self.wd)

            if item["test_image"] == None:
                _write_center(worksheet, "J" + str(temp), "", self.wd)
                worksheet.set_row(temp, 30)
            else:
                worksheet.insert_image('J' + str(temp), item["test_image"],
                                       {'x_scale': 0.1, 'y_scale': 0.1, 'border': 1})
                worksheet.set_row(temp - 1, 110)
            # if item["test_log"] != None:
            #     worksheet.write_url('O' + str(temp), item["test_log"], get_format(self.wd,
            #                                                                       {'bold': True, 'underline': 1,
            #                                                                        'valign': 'vcenter', 'border': 1}),
            #                         "下载日志")
            # else:
            #     _write_center(worksheet, "O" + str(temp), "", self.wd)
            temp = temp + 1

    def close(self):
        self.wd.close()


class OperateFile:
    # method(r,w,a)
    def __init__(self, file, method='w+'):
        self.file = file
        self.method = method
        self.fileHandle = None

    def write_txt(self, line):
        OperateFile(self.file).check_file()
        self.fileHandle = open(self.file, self.method)
        self.fileHandle.write(line + "\n")
        self.fileHandle.close()

    def read_txt_row(self):
        resutl = ""
        if OperateFile(self.file).check_file():
            self.fileHandle = open(self.file, self.method)
            resutl = self.fileHandle.readline()
            self.fileHandle.close()
        return resutl

    def read_txt_rows(self):
        if OperateFile(self.file).check_file():
            self.fileHandle = open(self.file, self.method)
            file_list = self.fileHandle.readlines()
            for i in file_list:
                print(i.strip("\n"))
            self.fileHandle.close()

    def check_file(self):
        if not os.path.isfile(self.file):
            return False
        else:
            return True

    def mkdir_file(self):
        if not os.path.isfile(self.file):
            f = open(self.file, self.method)
            f.close()
            print("创建文件成功")
        else:
            print("文件已经存在")

    def remove_file(self):
        if os.path.isfile(self.file):
            os.remove(self.file)
            print("删除文件成功")
        else:
            print("文件不存在")


# def link_format(wd):
#     red_format = wd.add_format({
#         'font_color': 'red',
#         'bold': 1,
#         'underline': 1,
#         'font_size': 12,
#     })


# 生成饼形图
# def pie(workbook, worksheet):
#     chart1 = workbook.add_chart({'type': 'pie'})
#     chart1.add_series({
#     'name':       '接口测试统计',
#     'categories':'=测试总况!$D$4:$D$5',
#    'values':    '=测试总况!$E$4:$E$5',
#     })
#     chart1.set_title({'name': '接口测试统计'})
#     chart1.set_style(10)
#     worksheet.insert_chart('A9', chart1, {'x_offset': 25, 'y_offset': 10})

if __name__ == '__main__':
    pass
    # data = {
    #     "test_date": "2016-12-01",
    #     "test_failed": 1,
    #     "info": [
    #         {
    #             "test_men_avg": "8%",
    #             "test_cpu_avg": "0%",
    #             "test_fps_avg": "0.00",
    #             "test_phone_raw": "1",
    #             "test_cpu_max": "0.0%",
    #             "test_intr": "闪退测试",
    #             "test_reason": "",
    #             "test_phone_name": "Huawei_H60-L02_android_4.4.2",
    #             "test_men_max": "23M",
    #             "test_image": None,
    #             "test_module": "闪退测试",
    #             "test_log": "",
    #             "test_fps_max": "0.0",
    #             "test_id": 1001,
    #             "test_result": "成功"
    #         },
    #         {
    #             "test_men_avg": "4%",
    #             "test_cpu_avg": "23%",
    #             "test_fps_avg": "0.00",
    #             "test_phone_raw": "1",
    #             "test_cpu_max": "46.0%",
    #             "test_intr": "闪退测试",
    #             "test_reason": "崩溃了",
    #             "test_phone_name": "Huawei_H60-L02_android_4.4.2",
    #             "test_men_max": "23M",
    #             "test_image": None,
    #             "test_module": "闪退测试",
    #             "test_log": "d://storage/emulated/0/crash/2016-12-01-15-58-48.log",
    #             "test_fps_max": "0.0",
    #             "test_id": 1001,
    #             "test_result": "失败"
    #         }
    #     ],
    #     "test_sum_date": "24秒",
    #     "app_name": "monkneyTest",
    #     "test_success": 2,
    #     "app_size": "0M",
    #     "init": [
    #         {
    #             "phone_avg_use_raw": "8%",
    #             "phone_avg_use_cpu": "0%",
    #             "fps_avg": "0.00",
    #             "fps_max": "0.0",
    #             "phone_name": "Huawei_H60-L02_android_4.4.2",
    #             "phone_avg_max_use_cpu": "0.0%",
    #             "phone_max_use_raw": "23M",
    #         },
    #         {
    #             "phone_name": "Huawei_H60-L02_android_4.4.2",
    #             "phone_avg_use_cpu": "0",
    #             "fps_avg": "0",
    #             "fps_max": "0",
    #             "phone_avg_use_raw": "0",
    #             "phone_max_use_raw": "0",
    #             "phone_avg_max_use_cpu": "0"
    #         }
    #     ],
    #     "test_sum": 3,
    #     "app_version": "1.0"
    # }
    # workbook = xlsxwriter.Workbook('testReport.xlsx')
    # worksheet = workbook.add_worksheet("测试总况")
    # worksheet2 = workbook.add_worksheet("测试详情")
    # bc = OperateReport(wd=workbook, data=data)
    # bc.init(worksheet)
    # bc.test_detail(worksheet2)
    # bc.close()
